package Bank;

import DBConnection.DBAPI;
import DBConnection.DBObject;
import org.apache.log4j.Logger;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;

public class TransactionPool implements TransactionPoolInterface {

    private static final Logger log = Logger.getLogger(TransactionPool.class);

    private static TransactionPool ourInstance = new TransactionPool();

    public static TransactionPool getInstance() {
        return ourInstance;
    }

    private TransactionPool() {
        pool = new LinkedList<>();
    }

    private LinkedList<BigInteger> pool;

    @Override
    public void addTransaction(Transaction transaction){
        HashMap<BigInteger, Object> attributes = new HashMap<>();
        attributes.put(DBAPI.ATTR_FROM, transaction.getSrc().getId());
        attributes.put(DBAPI.ATTR_TARGET, transaction.getTarget().getId());
        attributes.put(DBAPI.ATTR_INITIATOR, transaction.getInitiator().getId());
        attributes.put(DBAPI.ATTR_DATE, transaction.getDate());
        attributes.put(DBAPI.ATTR_COUNT, transaction.getSumm());
        attributes.put(DBAPI.ATTR_TRANSACTION_STATUS, transaction.getStatus().toString());
        BigInteger id = DBAPI.insertObject(new DBObject(transaction.getId(), DBAPI.TRANSACTION, "transaction from " + transaction.getSrc().getId().toString(), null, null, attributes));

        pool.add(transaction.getId());
        log.info("transaction " + id + " added");
    }

    @Override
    public Transaction getNextTransaction(){
        if (!pool.isEmpty()) {
            return DBAPI.getTransaction(DBAPI.getObject(pool.poll()));
        }
        return null;
    }

}
